import time

from base.device import DeviceBasic


class ProxyDroid(DeviceBasic):
    def __init__(self, device_client):
        super().__init__(device_client, "org.proxydroid")

    def get_switch_status(self):
        if not self.is_foreground():
            self.open()
        switch_widget = self._device(resourceId="android:id/switch_widget")
        status = self.wait_element(switch_widget, timeout=5)
        if not status:
            return None
        switch_widget_text = switch_widget.get_text()
        return switch_widget_text

    def open_switch(self) -> bool:
        if not self.is_foreground():
            self.open()
        if self.get_switch_status() == "开启":
            return True
        switch_widget = self._device(resourceId="android:id/switch_widget")
        status = self.wait_element(switch_widget, timeout=5)
        if not status:
            return False
        switch_widget.click()
        return self.get_switch_status() == "开启"

    def stop_switch(self):
        """
        关闭开关
        :return:
        """
        if not self.is_foreground():
            self.open()
        if self.get_switch_status() == "关闭":
            return True
        switch_widget = self._device(resourceId="android:id/switch_widget")
        status = self.wait_element(switch_widget, timeout=5)
        if not status:
            return False
        switch_widget.click()
        return self.get_switch_status() == "关闭"

    def set_host(self, host):
        result = self.stop_switch()
        if not result:
            return False
        host_element = self._device(resourceId="android:id/title", text="Host")
        if not self.wait_element(host_element, timeout=5):
            return False
        host_element.click()
        time.sleep(1)
        edit_element = self._device(resourceId="android:id/edit")
        edit_element.clear_text()
        time.sleep(1)
        edit_element.set_text(host)
        time.sleep(1)
        ok_button = self._device(resourceId="android:id/button1")
        ok_button.click()
        time.sleep(.5)
        return self.open_switch()
